import fetch from "../../utils/fetch";
const globalData = getApp().globalData;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isRegister: false, // 是否为注册页面
    userinfo: {
      avatar: "../../assets/defaultimg.png",
      username: '',
      age: '',
      sex: '',
      height: '',
      weight: '',
      targetWeight: '',
      college: ''
    },
    oldImg: '', //保存旧图片，文件上传失败的时候仍然使用旧图片
    heightArr: [],
    weightArr: [],
    heightIndex: 100, // picker默认选中的heightArr下标
    weightIndex: 40, // picker默认选中的weightArr下标
    targetWeightIndex: 40
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let info;
    if (options.isRegister) {
      info = this.data.userinfo;
    } else {
      info = globalData.userInfo;
    }
    // 初始化身高体重数组
    for (let i = 50; i <= 250; i++) {
      this.data.heightArr.push(i);
    }
    for (let i = 10; i <= 150; i++) {
      this.data.weightArr.push(i);
    }
    this.setData({
      heightArr: this.data.heightArr,
      weightArr: this.data.weightArr,
      userinfo: info,
      isRegister: options.isRegister
    })
  },
  // 选择身高
  selectHeight(e) {
    const index = e.detail.value;
    const height = parseInt(this.data.heightArr[index]);
    this.setData({
      'userinfo.height': height,
      heightIndex: index
    })
  },
  // 选择体重
  selectWeight(e) {
    const index = e.detail.value;
    const weight = parseInt(this.data.weightArr[index]);
    this.setData({
      'userinfo.weight': weight,
      weightIndex: index
    })
  },
  selectTargetWeight(e) {
    const index = e.detail.value;
    const targetWeight = parseInt(this.data.weightArr[index]);
    this.setData({
      'userinfo.targetWeight': targetWeight,
      targetWeightIndex: index
    })
  },
  //选择头像
  onChooseAvatar: function (e) {
    this.uploadAvatar(e.detail.avatarUrl);
  },
  // 上传头像
  uploadAvatar(file) {
    const that = this; // 保存this指针
    // 读配置获取baseUrl
    const app = getApp(); // 获取app对象实例
    const baseUrl = app.getConfig("baseUrl");
    wx.uploadFile({
      url: baseUrl + '/users/upload',
      filePath: file,
      name: 'file',
      success(res) {
        const imgUrl = JSON.parse(res.data).data.imageUrl;
        that.setData({
          'userinfo.avatar': imgUrl
        })
        // 上传成功，更改旧图片
        that.oldImg = imgUrl;
      },
      fail() {
        that.setData({
          'userinfo.avatar': that.oldImg,
        })
      }
    })
  },
  updateUser() {
    fetch('/users/update', {
      userData: this.data.userinfo
    }, 'post').then(res => {
      wx.hideLoading();
      const user = res.data.user;
      wx.setStorageSync('userInfo', user);
      globalData.userInfo = user;
      const pages = getCurrentPages();
      const prePage = pages[pages.length - 2];
      prePage.setData({
        info: this.data.info
      });
      wx.navigateBack();
      wx.showToast({
        title: '信息修改成功'
      })
    })
  },
  save(e) {
    const {
      avatar,
      college
    } = this.data.userinfo;
    if (avatar == "../../assets/defaultimg.png") {
      wx.showModal({
        title: '头像',
        content: '请更换默认头像',
        showCancel: false
      });
      return;
    }
    const {
      username,
      age,
      sex,
      weight,
      height,
      targetWeight
    } = e.detail.value;
    if (college && username && age && height && weight && targetWeight) {
      this.data.userinfo.username = username;
      this.data.userinfo.age = parseInt(age);
      this.data.userinfo.sex = parseInt(sex);
      this.data.userinfo.weight = parseInt(weight);
      this.data.userinfo.height = parseInt(height);
      this.data.userinfo.targetWeight = parseInt(targetWeight);
      wx.showLoading({
        title: '保存中'
      })
      if (this.data.isRegister) {
        this.regesiter();
      } else {
        // 修改用户信息
        this.updateUser();
      }
    }else{
      wx.showModal({
        title:'信息不完整',
        content:'请将个人信息填写完成才能进行注册',
        showCancel:false
      });
    }
  },
  regesiter() {
    const that = this;
    wx.login({
      success(res) {
        fetch('/users/register', {
          userData: that.data.userinfo,
          js_code: res.code
        }, 'post').then(res => {
          wx.hideLoading();
          const token = res.data.token;
          const user = res.data.user;
          // 存入缓存
          wx.setStorageSync('token', token);
          wx.setStorageSync('userInfo', user);
          globalData.userInfo = user;
          globalData.isLogin = true;
          globalData.token = token;
          const pages = getCurrentPages();
          const prepage = pages[pages.length - 2];
          prepage.setData({
            isLogin: true,
            userInfo: user
          });
          wx.navigateBack();
          wx.showToast({
            title: '注册成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/mine/mine'
            })
          }, 2000)
        })
      }
    })
  },
  changeCollege() {
    wx.navigateTo({
      url: '../college/college',
    })
  }
})